package com.vpx.server.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vpx.server.bean.constant.FileConstant;
import com.vpx.server.bean.entity.SysAttach;
import com.vpx.server.bean.info.base.UserInfo;
import com.vpx.server.bean.order.system.AttachDownLoadOrder;
import com.vpx.server.bean.order.system.AttachIdsOrder;
import com.vpx.server.bean.order.system.AttachUploadOrder;
import com.vpx.server.bean.result.system.AttachUploadResult;
import com.vpx.server.bean.result.system.SysAttachListResult;
import com.vpx.server.framework.aop.ServiceHandler;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.exception.BizException;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.mapper.system.SysAttachMapper;
import com.vpx.server.service.system.SysAttachService;
import com.vpx.server.utils.UserLoginUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author denglw
 * @title: vpx
 * @module system
 * @description: 附件管理
 * @date 2021/9/16 10:37
 */
@Service
public class SysAttachServiceImpl implements SysAttachService {
    private static final Logger log = LoggerFactory.getLogger(SysAttachServiceImpl.class);
    @Resource
    private SysAttachMapper sysAttachMapper;


    @Override
    @ServiceHandler(memo = "上传附件", isTransaction = true)
    public ResultMsg<AttachUploadResult> upload(AttachUploadOrder order) {
        String dirPath = System.getProperty("user.dir") + FileConstant.ATTACH_PATH;
        File directory = new File(dirPath);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                throw new BizException(String.format("创建目录%s失败", dirPath));
            }
        }
        String urlFileName = this.getGenFileName();
        String[] strArray = order.getFileName().split("\\.");
        int suffixIndex = strArray.length - 1;
        String suffix = strArray[suffixIndex];
        String fileUrl = dirPath + urlFileName + "." + suffix;
        try {
            FileOutputStream fos = new FileOutputStream(fileUrl);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = order.getFileInputStream().read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            Date now = DateUtils.now();
            UserInfo userInfo = UserLoginUtils.getCurrentUser();
            SysAttach attach = new SysAttach();
            attach.setAttachId(urlFileName);
            attach.setFileName(order.getFileName());
            attach.setFileUrl(fileUrl);
            attach.setSuffix(suffix);
            attach.setOperatorName(userInfo.getUserName());
            attach.setCreateUserId(userInfo.getId());
            attach.setUpdateUserId(userInfo.getId());
            attach.setCreateTime(now);
            attach.setUpdateTime(now);
            sysAttachMapper.insert(attach);
            AttachUploadResult result = new AttachUploadResult();
            result.setAttachId(attach.getAttachId());
            result.setFileName(order.getFileName());
            return ResultMsg.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
    }

    @Override
    @ServiceHandler(memo = "下载文件")
    public ResultMsg<AttachUploadResult> download(AttachDownLoadOrder order) {
        SysAttach attach = sysAttachMapper.findByAttachId(order.getAttachId());
        if (attach == null) {
            throw new BizException("附件不存在");
        }
        AttachUploadResult result = new AttachUploadResult();
        result.from(attach);
        return ResultMsg.success(result);
    }

    @Override
    @ServiceHandler(memo = "附件列表查询")
    public ResultMsg<SysAttachListResult> findAttachList(AttachIdsOrder order) {
        List<SysAttach> sysAttachList = sysAttachMapper.findByAttachIds(order.getAttachIds());
        SysAttachListResult result = new SysAttachListResult();
        result.setAttachList(sysAttachList);
        return ResultMsg.success(result);
    }

    /**
     * 生成文件名
     *
     * @return
     */
    private String getGenFileName() {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return dateFormat.format(new Date()) + RandomStringUtils.randomAlphanumeric(13);
    }
}
